package com.example.demo.intercept;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Login;
import com.example.demo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : 杨丽辉
 * @date : 2021/1/7 14:58
 * @description:
 */
@Component
public class AdminIntercept implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    /***
     * 返回错误信息
     */
    private void setReturn(HttpServletResponse response,
                           int status,
                           String msg) throws IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            JSONObject res = new JSONObject();
            res.put("errno", status);
            res.put("errmsg", msg);
            res.put("curtime", System.currentTimeMillis());
            out = response.getWriter();
            out.append(res.toString());
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
        }
    }


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //从redis获取用户相关信息
        String token = request.getHeader("token");
        Object o = redisUtil.get(token + ":authors");

        if (ObjectUtils.isEmpty(o)) {
            //token失效
            setReturn(response, 20012, "用户登录凭证已失效，请重新登录");
            return false;
        }

        String str = (String) o;
        Login login = JSON.parseObject(str, Login.class);
        request.setAttribute("tokenInfo", login);

        redisUtil.set(token + ":authors", o, 60 * 30);

        return true;
    }

}
